import React, { useEffect, useRef } from 'react'
import "./style.less"

/**
 * 判断触底!
 *     文档高度 = 视口高度 + 滚动高度 + 30px
 *     getBoundingClientRect()方法:次方法可以获得元素距离顶部的高度,随着滚动高度的变化，他实时发生变化
 *         left\top\bottom\right
 * 
 * 回流重绘
 * 节流防抖：在一定的期限值中(300ms)，只执行一次
 *     防抖(debounce)：最后一次为准
 *     节流(throttle)：第一次为准
 * 
 */

export default function LoadMore (props) {


  const loadContainer = useRef(null)
  useEffect(() => {
    // console.log(222);
    const winHeight = document.documentElement.clientHeight;
    let timer = null;

    window.addEventListener("scroll", () => {
      if (props.hasMore) {
        if (loadContainer.current) {
          let scrollHeight = loadContainer.current.getBoundingClientRect().top;
          // console.log(scrollHeight);
          if (winHeight > scrollHeight) {
            if (timer) {
              clearTimeout(timer)
            }
            timer = setTimeout(() => {
              props.onLoadMore()
            }, 300)
          }
        }
      }
    })

  }, [])



  return (
    <div className="load-more">
      <p ref={loadContainer}>加载更多</p>
    </div>
  )
}
